package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/3/15 0015.
 */

public class BindZhifuBaoActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.ed_name)
    EditText edName;
    @Bind(R.id.ed_zh)
    EditText edZh;
    @Bind(R.id.phone)
    TextView phone;
    @Bind(R.id.ed_code)
    EditText edCode;
    @Bind(R.id.tvcode)
    TextView tvcode;
    @Bind(R.id.bind)
    TextView bind;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private String telcode;
    private String seceret;
    private String sessionId;
    private int typeId;

    @Override
    public int bindLayout() {
        return R.layout.activity_zhifubao;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        title.setText("绑定支付宝");
        back.setOnClickListener(this);
        bind.setOnClickListener(this);
        tvcode.setOnClickListener(this);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        telcode = sp.getString("code", "");
        getSessionId();
        phone.setText(sp.getString("userPhone", ""));
        edName.setText(sp.getString("userName",""));
        edZh.setText(sp.getString("AliAccount",""));
        edName.addTextChangedListener(textWatcher);
        edZh.addTextChangedListener(textWatcher);
        edCode.addTextChangedListener(textWatcher);
        edName.setSelection(edName.getText().toString().length());
    }

    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!edName.getText().toString().trim().equals("") && edName.getText().toString().length() > 1 && !TextUtils.isEmpty(edName.getText()) && !edZh.getText().toString().trim().equals("") && !TextUtils.isEmpty(edZh.getText()) && !TextUtils.isEmpty(edCode.getText())) {
                bind.setBackgroundResource(R.drawable.edittext_style_orange_backgroung);
                bind.setEnabled(true);
            } else {
                bind.setBackgroundResource(R.drawable.edittext_style_dark);
                bind.setEnabled(false);
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.tvcode: {
                if (RegexValidateUtils.checkCellphone(phone.getText().toString())) {
                    typeId = 1;
                } else {
                    typeId = 2;
                }
                getCode();
            }
            break;
            case R.id.bind: {
                if (null == telcode || !edCode.getText().toString().equals(telcode)) {
                    ToastUtils.getInstance(this).showMessage("验证码错误");
                    return;
                }
                SetUserAlipay();

            }
            break;
            default:
                break;
        }
    }

    public void getCode() {
        timer.start();
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetCode(phone.getText().toString().trim(), typeId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "phone" + phone.getText().toString().trim() + "typeId" + typeId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(BindZhifuBaoActivity.this).showMessage("发送异常");
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    ToastUtils.getInstance(BindZhifuBaoActivity.this).showMessage(json.getString("message"));
                    telcode = json.getString("data");
                    editor.putString("code", telcode);
                    editor.apply();
                } else if (json.get("code").equals("-1")) {
                    ToastUtils.getInstance(BindZhifuBaoActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }

    public void SetUserAlipay() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).SetUserAlipay(sessionId, edName.getText().toString().trim(), edZh.getText().toString().trim(), phone.getText().toString().trim(), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserName" + edName.getText().toString().trim() + "UserAlipay" + edZh.getText().toString().trim() + "UserPhone" + phone.getText().toString().trim())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    ToastUtils.getInstance(BindZhifuBaoActivity.this).showMessage("绑定成功");
                    editor.putString("userName", edName.getText().toString().trim());
                    editor.putString("AliAccount", edZh.getText().toString().trim());
                    editor.apply();
                    finish();
                } else if (json.get("code").equals("-1")) {
                    ToastUtils.getInstance(BindZhifuBaoActivity.this).showMessage("绑定失败");
                } else if (json.get("code").equals("-2")) {
                    ToastUtils.getInstance(BindZhifuBaoActivity.this).showMessage("请输入真实姓名");
                }
            }
        });
    }

    /**
     * 取消倒计时
     *
     * @param v
     */
    public void oncancel(View v) {
        timer.cancel();
    }

    /**
     * 开始倒计时
     *
     * @param v
     */
    public void restart(View v) {
        timer.start();
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvcode.setEnabled(false);
            tvcode.setTextColor(Color.GRAY);
            tvcode.setText((millisUntilFinished / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            tvcode.setEnabled(true);
            tvcode.setTextColor(getResources().getColor(R.color.theme_color));
            tvcode.setText("发送验证码");
            timer.cancel();
        }
    };

    public void getSessionId() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetSessionId(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    seceret = json.getString("data");
                    sessionId = json.getString("message");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != timer) {
            timer.cancel();
        }
    }
}
